package com.sishu.service.impl;

import com.sishu.mapper.*;
import com.sishu.pojo.*;
import com.sishu.pojo.dto.Assetsdto;
import com.sishu.pojo.VO.GameVo;
import com.sishu.pojo.dto.Studentdto;
import com.sishu.service.GameGroupService;
import com.sishu.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;


@Slf4j
@Service
public class GameGroupServiceimpl implements GameGroupService {


    @Resource
    private GamegroupsMapper gamegroupsMapper;

    @Resource
    private GameMapper gameMapper;

    @Resource
    private GusMapper gusMapper;

    @Resource
    private AssetMapper assetMapper;

    @Resource
    private RoleMapper roleMapper;

    @Override
    public Result addGroup(List<Studentdto> students) {
        log.info("students = " + students);

        //1.先查gamegroups表可以用的groupId

        Result result = new Result<>(200, "初始状态", true);
        HashSet<String> hashSet = new HashSet<>();
        // 判断传过来的学生id是否重复
        for (Studentdto student : students) {
            if (!hashSet.add(student.getSId())) {
                result = new Result<>(500, "添加失败，传输过来的学生id重复", false);
            }
        }
        hashSet.clear();
        if (result != null && result.getCode() == 500) {
            return result;
        }

        boolean flag = true;//默认都在数据库中
        for (Studentdto student : students) {//判断该学生是不是在数据库中
            result = checkstudent(student);
            if (!result.isSuccess()) {
                flag = false;
                break;
            }
        }


        if (flag) {
            Result result1 = addgamegroups();        //获得gameId和groupId

            if (!result1.isSuccess()) { //添加失败,游戏没有开始
                return result1;
            }

            Gamegroups data = (Gamegroups) result1.getData();
            log.info("data = " + data);

            //得到本场游戏的难度
            String difficulty = gameMapper.selectgame(data.getGameId()).getGameDifficulty();

            String gameDifficulty = gameMapper.selectgame(data.getGameId()).getGameDifficulty();
            if (gameDifficulty.equals("team")) {
                return new Result<>(202, "团队模式请用addteamgroup接口", false);
            }


            boolean flag1 = true; //默认是有角色模式  角色没有了
            //2.插入gus中间表  如果困难度模式为easy或者common,就没有角色  hard或者 team模式就随机生成角色
            for (Studentdto student : students) {
                if (student.getRoleId() == null) {
                    Gus gus = new Gus(null, data.getGroupId(), student.getSId(), 0, 0, 0, 0, null);//默认没有删除
                    gusMapper.insert(gus);
                } else {
                    //没有对应的角色
                    Gus gus = new Gus(null, data.getGroupId(), student.getSId(), student.getRoleId(), 0, 0, 0, null);//默认没有删除
                    gusMapper.insert(gus);
                }


            }

            //3.插入asset表
            //3.1 先查game表的难度

            //3.2 插入asset表
            if (gameDifficulty.equals("easy")) {
                for (Studentdto student : students) {
                    Asset asset = new Asset(null, student.getSId(), data.getGroupId(), 10000, 10000, 0);

                    assetMapper.insert(asset);
                }
            }
            if (gameDifficulty.equals("common")) {
                for (Studentdto student : students) {
                    Asset asset = new Asset(null, student.getSId(), data.getGroupId(), 5000, 5000, 0);
                    assetMapper.insert(asset);
                }
            }
            if (gameDifficulty.equals("hard")) {
                for (Studentdto student : students) {
                    Asset asset = new Asset(null, student.getSId(), data.getGroupId(), 5000, 5000, 0);
                    assetMapper.insert(asset);
                }
            }


            List<GameVo> list = gameMapper.selectgusroleandgamegroups(data.getGameId());
            log.info("list = " + list);


            return result1;

            //return new Result<>(200, "data", "添加组成功", data, true);

            //return new Result<>(200, "list", list, "添加组成功", true);

        }
        return new Result<>(202, "添加失败，没有此学生", false);
    }

    @Override
    public Result addTeamGroup(List<TeamStudent> students) {
        log.info("students = " + students);

        //1.先查gamegroups表可以用的groupId

        boolean flag2 = true; //默认有
        for (TeamStudent student : students) {
            if (student.getTeam() == null) {
                flag2 = false;
                break;
            }
        }
        if (!flag2) {
            return new Result<>(202, "参数有误，必须有team值", false);
        }


        Result result = new Result<>(200, "初始状态", true);
        HashSet<String> hashSet = new HashSet<>();

        // 判断传过来的学生id是否重复
        for (TeamStudent student : students) {
            if (!hashSet.add(student.getSId())) {
                result = new Result<>(500, "添加失败，传输过来的学生id重复", false);
            }
        }
        hashSet.clear();
        if (result.getCode() == 500) {
            return result;
        }

        boolean flag = true;//默认都在数据库中
        for (TeamStudent student : students) {//判断该学生是不是在数据库中
            result = checkteamstudent(student);
            if (!result.isSuccess()) {
                flag = false;
                break;
            }
        }

        if (flag) {
            Result result1 = addteamgamegroups();        //获得gameId和groupId

            if (!result1.isSuccess()) { //添加失败,游戏没有开始
                return result1;
            }

            Gamegroups data = (Gamegroups) result1.getData();
            log.info("data = " + data);

            //2.插入gus中间表  如果困难度模式为easy或者common,就没有角色  hard或者 team模式就随机生成角色
            for (TeamStudent student : students) {

                Result addroles = addroles();//获取随机角色
                Role data1 = (Role) addroles.getData();
                // Gus gus = new Gus(null, data.getGroupId(), student.getSId(), data1.getRoleId(), 0, 0, 0, student.getTeam());//默认没有删除
                //   gusMapper.insert(gus);

            }

//
//            HashSet<String> hashSet2 = new HashSet<>();
//            for (TeamStudent student : students) {
//                hashSet2.add(student.getTeam());  //t1 t2
//            }

            for (TeamStudent student : students) {
                Asset asset = new Asset(null, student.getSId(), data.getGroupId(), 5000, 5000, 0);
                assetMapper.insert(asset);
            }


            List<GameVo> list = gameMapper.selectgusroleandgamegroups(data.getGameId());

            return new Result<>(200, "list", list, "添加组成功", true);

        }
        return new Result<>(202, "添加失败，没有此学生", false);
    }

    /**
     * @author linyi
     * @date 2025-01-03 10:31:17
     * @description 判断学生id是否在数据库中存在, 存在返回true, 不存在返回false
     */

    @Override
    public Result checkstudent(Studentdto student) {
        int checkstudent = gamegroupsMapper.checkstudent(student);
        if (checkstudent == 0)
            return new Result<>(202, "添加失败，学生id不存在", false);
        else
            return new Result<>(202, "添加成功", true);

    }

    @Override
    public Result checkteamstudent(TeamStudent student) {
        int checkstudent = gamegroupsMapper.checkteamstudent(student);
        if (checkstudent == 0)
            return new Result<>(202, "添加失败，学生id不存在", false);
        else
            return new Result<>(202, "添加成功", true);

    }

    @Override
    public Result selcetgroupasset(String groupId) {

        Gamegroups gamegroups = gamegroupsMapper.selectbygroupId(groupId);
        log.info("gamegroups = " + gamegroups);
        String gameId = gamegroups.getGameId();
        Game selectgame = gameMapper.selectgame(gameId); //查询gameId对应的game
        List<Assetsdto> selectbygroupid = new ArrayList<>();

        log.info("selectgameiffculty = " + selectgame.getGameDifficulty());
        if (selectgame.getGameDifficulty().equals("easy") || selectgame.getGameDifficulty().equals("common")) {
            selectbygroupid = assetMapper.selectbygroupid2(groupId);

            for (Assetsdto assetsdto : selectbygroupid) {

                assetsdto.setLevelName("无");
            }

            return new Result<>(200, "list1", selectbygroupid, "查询成功", true);

        } else {
            //如果roleId 有的话, 查询角色信息
            selectbygroupid = assetMapper.selectbygroupid(groupId);

            return new Result<>(200, "list2", selectbygroupid, "查询成功", true);
        }


    }

    public Result addgamegroups() {
        LocalDateTime time = LocalDateTime.now();
        //查询在endtime之前的game小组
        List<Game> games = gameMapper.selectAll(time);
        if (games == null || games.isEmpty()) {
            return new Result<>(202, "添加失败，等待时间已经结束,请等待下一把游戏", false);
        }
        Game game = games.get(0);
        //查询gameId对应的没使用过的gamegroups(avtive = 0)
        List<Gamegroups> gamegroups = gamegroupsMapper.selectbygameId(game.getGameId());
        if (gamegroups == null || gamegroups.isEmpty()) {
            return new Result<>(202, "添加失败，没有可用的小组", false);
        }

        log.info("gamegroups = " + gamegroups);
        // 创建一个 0 到 size - 1 之间的随机数

        try { //当六个小组添加满时,再次添加就会抛出异常
            int randomIndex = ThreadLocalRandom.current().nextInt(gamegroups.size());
            log.info("Random index = " + randomIndex);
            Gamegroups gamegroups1 = gamegroups.get(randomIndex);
            gamegroupsMapper.setactiveone(gamegroups1.getGroupId());  //设置已经被使用了
            return new Result<>(200, "data", "添加组成功", gamegroups1, true);
        } catch (Exception e) {
            return new Result<>(202, "添加失败，没有可用的小组", false);
        }

    }

    public Result addteamgamegroups() {
        LocalDateTime time = LocalDateTime.now();
        //查询在endtime之前的game小组
        List<Game> games = gameMapper.selectAll(time);
        if (games == null || games.isEmpty()) {
            return new Result<>(202, "添加失败，等待时间已经结束,请等待游戏结束", false);
        }

        boolean flag = false;
        for (Game game : games) {
            if (game.getGameDifficulty().equals("team")) {
                flag = true;
                break;
            }
        }
        if (!flag)
            return new Result(500, "添加失败，游戏没有开启团队模式", false);

        Game game = games.get(0);
        //查询gameId对应的没使用过的gamegroups(avtive = 0)
        List<Gamegroups> gamegroups = gamegroupsMapper.selectbygameId(game.getGameId());
        log.info("gamegroups = " + gamegroups);
        // 创建一个 0 到 size - 1 之间的随机数

        try { //当六个小组添加满时,再次添加就会抛出异常
            int randomIndex = ThreadLocalRandom.current().nextInt(gamegroups.size());
            log.info("Random index = " + randomIndex);
            Gamegroups gamegroups1 = gamegroups.get(randomIndex);
            gamegroupsMapper.setactiveone(gamegroups1.getGroupId());  //设置已经被使用了
            return new Result<>(200, "data", "添加组成功", gamegroups1, true);
        } catch (Exception e) {
            return new Result<>(202, "添加失败，没有可用的小组", false);
        }

    }


    public Result addroles() {

        //查询level1对应的所有职业
        List<Role> roles = roleMapper.selectRoleBylevel(1);
        log.info("roles = " + roles);
        // 创建一个 0 到 size - 1 之间的随机数
        int randomIndex = ThreadLocalRandom.current().nextInt(roles.size());
        log.info("Random index = " + randomIndex);
        Role role = roles.get(randomIndex);
        log.info("role = " + role);
        return new Result<>(200, "data", "添加角色成功", role, true);
    }

}
